#include "execution/execution_engine.h"
#include <iostream>
#include <random>
#include <thread>
#include <chrono>
#include <sstream>

namespace hft {

SimulatedExecutionEngine::SimulatedExecutionEngine()
    : is_connected_(false), simulated_latency_ms_(10), fill_probability_(0.8), next_trade_id_(1) {
}

bool SimulatedExecutionEngine::sendOrder(const Order& order) {
    if (!is_connected_) {
        std::cerr << "SimulatedExecutionEngine not connected" << std::endl;
        return false;
    }
    
    // 模拟网络延迟
    if (simulated_latency_ms_ > 0) {
        std::this_thread::sleep_for(std::chrono::milliseconds(simulated_latency_ms_));
    }
    
    // 创建订单副本
    Order order_copy = order;
    
    // 更新订单状态
    order_copy.status = OrderStatus::Pending;
    
    // 通知订单状态更新
    if (order_callback_) {
        order_callback_(order_copy);
    }
    
    // 模拟订单匹配
    std::thread([this, order_copy]() {
        // 再次模拟一些处理延迟
        if (simulated_latency_ms_ > 0) {
            std::this_thread::sleep_for(std::chrono::milliseconds(simulated_latency_ms_));
        }
        
        // 处理订单匹配
        Order mutable_order = order_copy;
        processOrderMatch(mutable_order);
    }).detach();
    
    return true;
}

bool SimulatedExecutionEngine::modifyOrder(const Order& order) {
    if (!is_connected_) {
        std::cerr << "SimulatedExecutionEngine not connected" << std::endl;
        return false;
    }
    
    // 模拟网络延迟
    if (simulated_latency_ms_ > 0) {
        std::this_thread::sleep_for(std::chrono::milliseconds(simulated_latency_ms_));
    }
    
    // 创建订单副本
    Order order_copy = order;
    
    // 通知订单状态更新
    if (order_callback_) {
        order_callback_(order_copy);
    }
    
    // 模拟订单匹配
    std::thread([this, order_copy]() {
        // 再次模拟一些处理延迟
        if (simulated_latency_ms_ > 0) {
            std::this_thread::sleep_for(std::chrono::milliseconds(simulated_latency_ms_));
        }
        
        // 处理订单匹配
        Order mutable_order = order_copy;
        processOrderMatch(mutable_order);
    }).detach();
    
    return true;
}

bool SimulatedExecutionEngine::cancelOrder(const Order& order) {
    if (!is_connected_) {
        std::cerr << "SimulatedExecutionEngine not connected" << std::endl;
        return false;
    }
    
    // 模拟网络延迟
    if (simulated_latency_ms_ > 0) {
        std::this_thread::sleep_for(std::chrono::milliseconds(simulated_latency_ms_));
    }
    
    // 创建订单副本
    Order order_copy = order;
    
    // 更新订单状态
    order_copy.status = OrderStatus::Canceled;
    
    // 通知订单状态更新
    if (order_callback_) {
        order_callback_(order_copy);
    }
    
    return true;
}

void SimulatedExecutionEngine::setOrderCallback(std::function<void(const Order&)> callback) {
    order_callback_ = callback;
}

void SimulatedExecutionEngine::setTradeCallback(std::function<void(const Trade&)> callback) {
    trade_callback_ = callback;
}

bool SimulatedExecutionEngine::connect() {
    is_connected_ = true;
    return true;
}

void SimulatedExecutionEngine::disconnect() {
    is_connected_ = false;
}

bool SimulatedExecutionEngine::isConnected() const {
    return is_connected_;
}

int64_t SimulatedExecutionEngine::getExchangeTime() const {
    auto now = std::chrono::system_clock::now();
    return std::chrono::duration_cast<std::chrono::milliseconds>(
        now.time_since_epoch()).count();
}

void SimulatedExecutionEngine::updateMarketPrice(const std::string& symbol, double price) {
    market_prices_[symbol] = price;
}

void SimulatedExecutionEngine::setSimulatedLatency(int latency_ms) {
    simulated_latency_ms_ = latency_ms;
}

void SimulatedExecutionEngine::setFillProbability(double probability) {
    fill_probability_ = std::max(0.0, std::min(1.0, probability));
}

void SimulatedExecutionEngine::processOrderMatch(Order& order) {
    // 检查是否有市场价格
    auto it = market_prices_.find(order.symbol);
    if (it == market_prices_.end()) {
        // 没有市场价格，无法匹配
        return;
    }
    
    double market_price = it->second;
    
    // 随机数生成器
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(0.0, 1.0);
    
    // 根据订单类型和价格决定是否成交
    bool should_fill = false;
    double fill_price = 0.0;
    
    if (order.type == OrderType::Market) {
        // 市价单总是成交
        should_fill = true;
        fill_price = market_price;
    } else if (order.type == OrderType::Limit) {
        // 限价单只有当价格合适时才成交
        if ((order.side == OrderSide::Buy && order.price >= market_price) ||
            (order.side == OrderSide::Sell && order.price <= market_price)) {
            should_fill = dis(gen) <= fill_probability_;
            fill_price = order.price;
        }
    } else if (order.type == OrderType::Stop) {
        // 止损单只有当价格突破止损价时才成交
        if ((order.side == OrderSide::Buy && market_price >= order.stop_price) ||
            (order.side == OrderSide::Sell && market_price <= order.stop_price)) {
            should_fill = dis(gen) <= fill_probability_;
            fill_price = market_price;
        }
    } else if (order.type == OrderType::StopLimit) {
        // 止损限价单需要价格突破止损价，并且限价合适
        if ((order.side == OrderSide::Buy && market_price >= order.stop_price && order.price >= market_price) ||
            (order.side == OrderSide::Sell && market_price <= order.stop_price && order.price <= market_price)) {
            should_fill = dis(gen) <= fill_probability_;
            fill_price = order.price;
        }
    }
    
    if (should_fill) {
        // 决定成交数量
        int remaining_volume = order.volume - order.filled_volume;
        int fill_volume = remaining_volume;
        
        // 有时候只部分成交
        if (dis(gen) > 0.7) {
            fill_volume = static_cast<int>(remaining_volume * dis(gen));
            if (fill_volume <= 0) {
                fill_volume = 1;
            }
        }
        
        // 生成成交
        generateSimulatedTrade(order, fill_volume, fill_price);
        
        // 更新订单状态
        order.filled_volume += fill_volume;
        if (order.filled_volume >= order.volume) {
            order.status = OrderStatus::Filled;
        } else {
            order.status = OrderStatus::PartialFilled;
        }
        
        // 通知订单状态更新
        if (order_callback_) {
            order_callback_(order);
        }
        
        // 如果订单未完全成交，可能会在稍后再次成交
        if (order.status == OrderStatus::PartialFilled) {
            std::thread([this, order]() {
                // 等待一段时间
                std::this_thread::sleep_for(std::chrono::milliseconds(500 + simulated_latency_ms_));
                
                // 再次处理订单匹配
                Order mutable_order = order;
                processOrderMatch(mutable_order);
            }).detach();
        }
    }
}

void SimulatedExecutionEngine::generateSimulatedTrade(Order& order, int volume, double price) {
    Trade trade;
    trade.trade_id = std::to_string(next_trade_id_++);
    trade.order_id = order.order_id;
    trade.symbol = order.symbol;
    trade.side = order.side;
    trade.price = price;
    trade.volume = volume;
    trade.trade_time = std::chrono::system_clock::now();
    trade.exchange_trade_id = "sim-" + trade.trade_id;
    trade.account = order.account;
    trade.strategy_id = order.strategy_id;
    
    // 通知成交回报
    if (trade_callback_) {
        trade_callback_(trade);
    }
}

} // namespace hft